{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9cAP_u-vTO2Z"
      },
      "source": [
        "# Building RAG with Elastic and [Mistral](https://docs.mistral.ai/getting-started/quickstart/)\n",
        "\n",
        "This notebook is a hands-on demonstration of how to create a multilingual RAG system. The following steps were extracted from the article [\"Building RAG with Elastic and Mistral\"](https://www.elastic.co/search-labs/blog/building-multilingual-rag-with-elastic-and-mistral).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ih4ku-GGVC8P"
      },
      "source": [
        "## Install Packages and Import Necessary Modules\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rt5UtcodVCP4",
        "outputId": "4fa1ecd6-e0e7-4585-ff36-31c04ea6cda5"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Collecting elasticsearch==8.14\n",
            "  Downloading elasticsearch-8.14.0-py3-none-any.whl (480 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m480.2/480.2 kB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting mistralai\n",
            "  Downloading mistralai-0.4.2-py3-none-any.whl (20 kB)\n",
            "Collecting elastic-transport<9,>=8.13 (from elasticsearch==8.14)\n",
            "  Downloading elastic_transport-8.13.1-py3-none-any.whl (64 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m64.5/64.5 kB\u001b[0m \u001b[31m7.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting httpx<1,>=0.25 (from mistralai)\n",
            "  Downloading httpx-0.27.0-py3-none-any.whl (75 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.6/75.6 kB\u001b[0m \u001b[31m9.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting orjson<3.11,>=3.9.10 (from mistralai)\n",
            "  Downloading orjson-3.10.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (141 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m141.1/141.1 kB\u001b[0m \u001b[31m5.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: pydantic<3,>=2.5.2 in /usr/local/lib/python3.10/dist-packages (from mistralai) (2.8.2)\n",
            "Requirement already satisfied: urllib3<3,>=1.26.2 in /usr/local/lib/python3.10/dist-packages (from elastic-transport<9,>=8.13->elasticsearch==8.14) (2.0.7)\n",
            "Requirement already satisfied: certifi in /usr/local/lib/python3.10/dist-packages (from elastic-transport<9,>=8.13->elasticsearch==8.14) (2024.7.4)\n",
            "Requirement already satisfied: anyio in /usr/local/lib/python3.10/dist-packages (from httpx<1,>=0.25->mistralai) (3.7.1)\n",
            "Collecting httpcore==1.* (from httpx<1,>=0.25->mistralai)\n",
            "  Downloading httpcore-1.0.5-py3-none-any.whl (77 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m77.9/77.9 kB\u001b[0m \u001b[31m6.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: idna in /usr/local/lib/python3.10/dist-packages (from httpx<1,>=0.25->mistralai) (3.7)\n",
            "Requirement already satisfied: sniffio in /usr/local/lib/python3.10/dist-packages (from httpx<1,>=0.25->mistralai) (1.3.1)\n",
            "Collecting h11<0.15,>=0.13 (from httpcore==1.*->httpx<1,>=0.25->mistralai)\n",
            "  Downloading h11-0.14.0-py3-none-any.whl (58 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m6.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: annotated-types>=0.4.0 in /usr/local/lib/python3.10/dist-packages (from pydantic<3,>=2.5.2->mistralai) (0.7.0)\n",
            "Requirement already satisfied: pydantic-core==2.20.1 in /usr/local/lib/python3.10/dist-packages (from pydantic<3,>=2.5.2->mistralai) (2.20.1)\n",
            "Requirement already satisfied: typing-extensions>=4.6.1 in /usr/local/lib/python3.10/dist-packages (from pydantic<3,>=2.5.2->mistralai) (4.12.2)\n",
            "Requirement already satisfied: exceptiongroup in /usr/local/lib/python3.10/dist-packages (from anyio->httpx<1,>=0.25->mistralai) (1.2.1)\n",
            "Installing collected packages: orjson, h11, elastic-transport, httpcore, elasticsearch, httpx, mistralai\n",
            "Successfully installed elastic-transport-8.13.1 elasticsearch-8.14.0 h11-0.14.0 httpcore-1.0.5 httpx-0.27.0 mistralai-0.4.2 orjson-3.10.6\n"
          ]
        }
      ],
      "source": [
        "# install packages\n",
        "!python3 -m pip install elasticsearch==8.14 mistralai\n",
        "\n",
        "# import modules\n",
        "from mistralai.client import MistralClient\n",
        "from mistralai.models.chat_completion import ChatMessage\n",
        "from elasticsearch import Elasticsearch, exceptions\n",
        "from elasticsearch.helpers import bulk\n",
        "from getpass import getpass\n",
        "import json"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MjWgSORkVN8S"
      },
      "source": [
        "## Declaring Variables\n",
        "\n",
        "This code will create inputs where you can enter your credentials.\n",
        "Here you can learn how to retrieve your Elasticsearch credentials: [Finding Your Cloud ID](https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#finding-your-cloud-id)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "FmLboc-eVNVf",
        "outputId": "cd6b1b3e-2acb-442f-b5e8-d745471dbbd4"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Elastic Cloud ID: ··········\n",
            "Elastic Api Key: ··········\n",
            "MISTRAL Api key: ··········\n"
          ]
        }
      ],
      "source": [
        "ELASTIC_CLUSTER_ID = getpass(\"Elastic Cloud ID: \")\n",
        "ELASTIC_API_KEY = getpass(\"Elastic Api Key: \")\n",
        "MISTRAL_API_KEY = getpass(\"MISTRAL Api key: \")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i4WSQcMLVXTy"
      },
      "source": [
        "## Instance a Elasticsearch client\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jRAuK5wOU3Dv"
      },
      "outputs": [],
      "source": [
        "# Create the client instance\n",
        "es_client = Elasticsearch(\n",
        "    cloud_id=ELASTIC_CLUSTER_ID,\n",
        "    api_key=ELASTIC_API_KEY,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C3-RNJr9UQkt"
      },
      "source": [
        "## Creating embeddings endpoint\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VYoqPlZPQ1vF",
        "outputId": "983c8b49-4fd9-4010-f074-e75b94658f82"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Embedding endpoint created successfully.\n"
          ]
        }
      ],
      "source": [
        "try:\n",
        "    es_client.options(\n",
        "        request_timeout=60, max_retries=3, retry_on_timeout=True\n",
        "    ).inference.put_model(\n",
        "        task_type=\"text_embedding\",\n",
        "        inference_id=\"multilingual_embeddings\",\n",
        "        body={\n",
        "            \"service\": \"elasticsearch\",\n",
        "            \"service_settings\": {\n",
        "                \"model_id\": \".multilingual-e5-small\",\n",
        "                \"num_allocations\": 1,\n",
        "                \"num_threads\": 1,\n",
        "            },\n",
        "        },\n",
        "    )\n",
        "\n",
        "    print(\"Embedding endpoint created successfully.\")\n",
        "except exceptions.BadRequestError as e:\n",
        "    if e.error == \"resource_already_exists_exception\":\n",
        "        print(\"Embedding endpoint already created.\")\n",
        "    else:\n",
        "        raise e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zB52lDsuVzwP"
      },
      "source": [
        "## Creating Mappings\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JL6irDwHTCmF"
      },
      "outputs": [],
      "source": [
        "try:\n",
        "    es_client.indices.create(\n",
        "        index=\"multilingual-mistral\",\n",
        "        body={\n",
        "            \"mappings\": {\n",
        "                \"properties\": {\n",
        "                    \"super_body\": {\n",
        "                        \"type\": \"semantic_text\",\n",
        "                        \"inference_id\": \"multilingual-embeddings\",\n",
        "                    }\n",
        "                }\n",
        "            }\n",
        "        },\n",
        "    )\n",
        "except exceptions.RequestError as e:\n",
        "    if e.error == \"resource_already_exists_exception\":\n",
        "        print(\"Index already exists.\")\n",
        "    else:\n",
        "        raise e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GmJAvo8MbSwb"
      },
      "source": [
        "## Indexing documents\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "G6HouDn335cO"
      },
      "outputs": [],
      "source": [
        "# Support tickets to add to the index\n",
        "support_tickets = [\n",
        "    \"\"\"\n",
        "        _Support Ticket #EN1234_\n",
        "        **Subject**: Calendar sync not working with Google Calendar\n",
        "\n",
        "        **Description**:\n",
        "        I'm having trouble syncing my project deadlines with Google Calendar. Whenever I try to sync, I get an error message saying \"Unable to connect to external calendar service.\"\n",
        "\n",
        "        **Resolution**:\n",
        "        The issue was resolved by following these steps:\n",
        "        1. Go to Settings > Integrations\n",
        "        2. Disconnect the Google Calendar integration\n",
        "        3. Clear browser cache and cookies\n",
        "        4. Reconnect the Google Calendar integration\n",
        "        5. Authorize the app again in Google's security settings\n",
        "\n",
        "        The sync should now work correctly. If problems persist, ensure that third-party cookies are enabled in your browser settings.\n",
        "    \"\"\",\n",
        "    \"\"\"\n",
        "        _Support-Ticket #DE5678_\n",
        "        **Betreff**: Datei-Upload funktioniert nicht\n",
        "\n",
        "        **Beschreibung**:\n",
        "        Ich kann keine Dateien mehr in meine Projekte hochladen. Jedes Mal, wenn ich es versuche, bleibt der Ladebalken bei 99% stehen und dann erscheint eine Fehlermeldung.\n",
        "\n",
        "        **Lösung**:\n",
        "        Das Problem wurde durch folgende Schritte gelöst:\n",
        "        1. Überprüfen Sie die Dateigröße. Die maximale Uploadgröße beträgt 100 MB.\n",
        "        2. Deaktivieren Sie vorübergehend den Virenschutz oder die Firewall.\n",
        "        3. Versuchen Sie, die Datei im Inkognito-Modus hochzuladen.\n",
        "        4. Wenn das nicht funktioniert, leeren Sie den Browser-Cache und die Cookies.\n",
        "        5. Als letzten Ausweg, versuchen Sie einen anderen Browser zu verwenden.\n",
        "\n",
        "        In den meisten Fällen lag das Problem an zu großen Dateien oder an Interferenzen durch Sicherheitssoftware. Nach Anwendung dieser Schritte sollte der Upload funktionieren.\n",
        "    \"\"\",\n",
        "    \"\"\"\n",
        "        _Q3 Marketing Campaign Ideas_\n",
        "\n",
        "        1. Social media contest: \"Share Your Productivity Hack\"\n",
        "        - Users share tips using our software, best entry wins a premium subscription\n",
        "\n",
        "        2. Webinar series: \"Mastering Project Management\"\n",
        "        - Invite industry experts to share insights using our tool\n",
        "\n",
        "        3. Email campaign: \"Unlock Hidden Features\"\n",
        "        - Series of emails highlighting lesser-known but powerful features\n",
        "\n",
        "        4. Partner with a productivity podcast for sponsored content\n",
        "\n",
        "        5. Create a \"Project Management Memes\" social media account for lighter, shareable content\n",
        "    \"\"\",\n",
        "    \"\"\"\n",
        "        _Mitarbeiter des Monats: Juli 2023_\n",
        "\n",
        "        Wir freuen uns, bekannt zu geben, dass Sarah Schmidt zur Mitarbeiterin des Monats Juli gewählt wurde!\n",
        "\n",
        "        Sarah hat außergewöhnliche Leistungen in folgenden Bereichen gezeigt:\n",
        "        - Kundenbetreuung: Sarah hat durchschnittlich 95% positive Bewertungen erhalten.\n",
        "        - Teamarbeit: Sie hat maßgeblich zur Verbesserung unseres internen Wissensmanagementsystems beigetragen.\n",
        "        - Innovation: Sarah hat eine neue Methode zur Priorisierung von Support-Tickets vorgeschlagen, die unsere Reaktionszeiten um 20% verbessert hat.\n",
        "\n",
        "        Bitte gratulieren Sie Sarah zu dieser wohlverdienten Anerkennung!\n",
        "    \"\"\",\n",
        "]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IFXay8mA7_vA"
      },
      "outputs": [],
      "source": [
        "# This function will create a bulk object for the given id and body\n",
        "def build_bulk_obj(id, body):\n",
        "    return {\n",
        "        \"_index\": \"multilingual-mistral\",\n",
        "        \"_id\": id,\n",
        "        \"_source\": {\"super_body\": body},\n",
        "    }"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "61wAGoeZ5ERE",
        "outputId": "399338fd-c47d-4082-c468-35d526714e66"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Data indexed successfully.\n"
          ]
        }
      ],
      "source": [
        "data = []\n",
        "\n",
        "# Constructing bulk object for each detail\n",
        "for i, details in enumerate(support_tickets):\n",
        "    data.append(build_bulk_obj(i + 1, details))\n",
        "\n",
        "try:\n",
        "    # Using the bulk API to index the data\n",
        "    bulk(es_client, data)\n",
        "    print(\"Data indexed successfully.\")\n",
        "except exceptions.RequestError as e:\n",
        "    print(\"Error indexing data.\")\n",
        "    print(e)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "29suVGshDVQz"
      },
      "source": [
        "## Retrieving documents\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "abbVMTRaDVQz",
        "outputId": "4cd7acdb-3f0f-4ddb-9b36-321661764d14"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "    \"took\": 48,\n",
            "    \"timed_out\": false,\n",
            "    \"_shards\": {\n",
            "        \"total\": 1,\n",
            "        \"successful\": 1,\n",
            "        \"skipped\": 0,\n",
            "        \"failed\": 0\n",
            "    },\n",
            "    \"hits\": {\n",
            "        \"total\": {\n",
            "            \"value\": 3,\n",
            "            \"relation\": \"eq\"\n",
            "        },\n",
            "        \"max_score\": 0.9155389,\n",
            "        \"hits\": [\n",
            "            {\n",
            "                \"_index\": \"multilingual-mistral\",\n",
            "                \"_id\": \"1\",\n",
            "                \"_score\": 0.9155389,\n",
            "                \"_source\": {\n",
            "                    \"super_body\": {\n",
            "                        \"inference\": {\n",
            "                            \"inference_id\": \"multilingual-embeddings\",\n",
            "                            \"model_settings\": {\n",
            "                                \"similarity\": \"cosine\",\n",
            "                                \"element_type\": \"float\",\n",
            "                                \"task_type\": \"text_embedding\",\n",
            "                                \"dimensions\": 384\n",
            "                            }\n",
            "                        },\n",
            "                        \"text\": \"\\n        _Support Ticket #EN1234_\\n        **Subject**: Calendar sync not working with Google Calendar\\n\\n        **Description**:\\n        I'm having trouble syncing my project deadlines with Google Calendar. Whenever I try to sync, I get an error message saying \\\"Unable to connect to external calendar service.\\\"\\n\\n        **Resolution**:\\n        The issue was resolved by following these steps:\\n        1. Go to Settings > Integrations\\n        2. Disconnect the Google Calendar integration\\n        3. Clear browser cache and cookies\\n        4. Reconnect the Google Calendar integration\\n        5. Authorize the app again in Google's security settings\\n\\n        The sync should now work correctly. If problems persist, ensure that third-party cookies are enabled in your browser settings.\\n    \"\n",
            "                    }\n",
            "                }\n",
            "            },\n",
            "            {\n",
            "                \"_index\": \"multilingual-mistral\",\n",
            "                \"_id\": \"2\",\n",
            "                \"_score\": 0.90574336,\n",
            "                \"_source\": {\n",
            "                    \"super_body\": {\n",
            "                        \"inference\": {\n",
            "                            \"inference_id\": \"multilingual-embeddings\",\n",
            "                            \"model_settings\": {\n",
            "                                \"similarity\": \"cosine\",\n",
            "                                \"element_type\": \"float\",\n",
            "                                \"task_type\": \"text_embedding\",\n",
            "                                \"dimensions\": 384\n",
            "                            }\n",
            "                        },\n",
            "                        \"text\": \"\\n        _Support-Ticket #DE5678_\\n        **Betreff**: Datei-Upload funktioniert nicht\\n\\n        **Beschreibung**:\\n        Ich kann keine Dateien mehr in meine Projekte hochladen. Jedes Mal, wenn ich es versuche, bleibt der Ladebalken bei 99% stehen und dann erscheint eine Fehlermeldung.\\n\\n        **L\\u00f6sung**:\\n        Das Problem wurde durch folgende Schritte gel\\u00f6st:\\n        1. \\u00dcberpr\\u00fcfen Sie die Dateigr\\u00f6\\u00dfe. Die maximale Uploadgr\\u00f6\\u00dfe betr\\u00e4gt 100 MB.\\n        2. Deaktivieren Sie vor\\u00fcbergehend den Virenschutz oder die Firewall.\\n        3. Versuchen Sie, die Datei im Inkognito-Modus hochzuladen.\\n        4. Wenn das nicht funktioniert, leeren Sie den Browser-Cache und die Cookies.\\n        5. Als letzten Ausweg, versuchen Sie einen anderen Browser zu verwenden.\\n\\n        In den meisten F\\u00e4llen lag das Problem an zu gro\\u00dfen Dateien oder an Interferenzen durch Sicherheitssoftware. Nach Anwendung dieser Schritte sollte der Upload funktionieren.\\n    \"\n",
            "                    }\n",
            "                }\n",
            "            }\n",
            "        ]\n",
            "    }\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "response = es_client.search(\n",
        "    index=\"multilingual-mistral\",\n",
        "    body={\n",
        "        \"size\": 2,\n",
        "        \"_source\": {\"excludes\": [\"*embeddings\", \"*chunks\"]},\n",
        "        \"query\": {\n",
        "            \"semantic\": {\n",
        "                \"field\": \"super_body\",\n",
        "                \"query\": \"Hola, estoy teniendo problemas para ocupar su aplicación, estoy teniendo problemas para sincronizar mi calendario, y encima al intentar subir un archivo me da error.\",\n",
        "            }\n",
        "        },\n",
        "    },\n",
        ")\n",
        "\n",
        "# Print results\n",
        "formatted_json = json.dumps(response.body, indent=4)\n",
        "\n",
        "print(formatted_json)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RPYoKwnMDVQz"
      },
      "source": [
        "## Answering the question\n",
        "\n",
        "Now we will use Mistral to answer the question.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1I7vTiXJvDG4"
      },
      "outputs": [],
      "source": [
        "# Joining the Elasticsearch retrieve context\n",
        "elastic_context = []\n",
        "\n",
        "for r in response.body[\"hits\"][\"hits\"]:\n",
        "    elastic_context.append(r[\"_source\"][\"super_body\"][\"text\"])\n",
        "\n",
        "context_str = \"\\n\".join(elastic_context)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "iVOuJFF3bQiD",
        "outputId": "ad30bd0a-75a8-42b6-f520-f051a84f74ed"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "    ## Question:\n",
            "\n",
            "    Hola, estoy teniendo problemas para ocupar su aplicación, estoy teniendo problemas para sincronizar mi calendario, y encima al intentar subir un archivo me da error.\n",
            "\n",
            "    ## Related knowledge:\n",
            "\n",
            "    \n",
            "        _Support Ticket #EN1234_\n",
            "        **Subject**: Calendar sync not working with Google Calendar\n",
            "\n",
            "        **Description**:\n",
            "        I'm having trouble syncing my project deadlines with Google Calendar. Whenever I try to sync, I get an error message saying \"Unable to connect to external calendar service.\"\n",
            "\n",
            "        **Resolution**:\n",
            "        The issue was resolved by following these steps:\n",
            "        1. Go to Settings > Integrations\n",
            "        2. Disconnect the Google Calendar integration\n",
            "        3. Clear browser cache and cookies\n",
            "        4. Reconnect the Google Calendar integration\n",
            "        5. Authorize the app again in Google's security settings\n",
            "\n",
            "        The sync should now work correctly. If problems persist, ensure that third-party cookies are enabled in your browser settings.\n",
            "    \n",
            "\n",
            "        _Support-Ticket #DE5678_\n",
            "        **Betreff**: Datei-Upload funktioniert nicht\n",
            "\n",
            "        **Beschreibung**:\n",
            "        Ich kann keine Dateien mehr in meine Projekte hochladen. Jedes Mal, wenn ich es versuche, bleibt der Ladebalken bei 99% stehen und dann erscheint eine Fehlermeldung.\n",
            "\n",
            "        **Lösung**:\n",
            "        Das Problem wurde durch folgende Schritte gelöst:\n",
            "        1. Überprüfen Sie die Dateigröße. Die maximale Uploadgröße beträgt 100 MB.\n",
            "        2. Deaktivieren Sie vorübergehend den Virenschutz oder die Firewall.\n",
            "        3. Versuchen Sie, die Datei im Inkognito-Modus hochzuladen.\n",
            "        4. Wenn das nicht funktioniert, leeren Sie den Browser-Cache und die Cookies.\n",
            "        5. Als letzten Ausweg, versuchen Sie einen anderen Browser zu verwenden.\n",
            "\n",
            "        In den meisten Fällen lag das Problem an zu großen Dateien oder an Interferenzen durch Sicherheitssoftware. Nach Anwendung dieser Schritte sollte der Upload funktionieren.\n",
            "    \n",
            "\n"
          ]
        }
      ],
      "source": [
        "client = MistralClient(api_key=MISTRAL_API_KEY)\n",
        "\n",
        "system_message = \"You are a helpful multilingual agent that help users with their problems. You have access to a knowledge base on different languages and you must answer in the same language the question was asked.\"\n",
        "user_message = f\"\"\"\n",
        "    ## Question:\n",
        "\n",
        "    Hola, estoy teniendo problemas para ocupar su aplicación, estoy teniendo problemas para sincronizar mi calendario, y encima al intentar subir un archivo me da error.\n",
        "\n",
        "    ## Related knowledge:\n",
        "\n",
        "    {context_str}\n",
        "\"\"\"\n",
        "\n",
        "messages = [\n",
        "    ChatMessage(role=\"system\", content=system_message),\n",
        "    ChatMessage(role=\"user\", content=user_message),\n",
        "]\n",
        "\n",
        "model = \"open-mixtral-8x22b\"\n",
        "\n",
        "chat_response = client.chat(\n",
        "    model=model,\n",
        "    messages=messages,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1tszu7ReDVQz"
      },
      "source": [
        "The answer is on point!\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fXTvNIw4DVQz",
        "outputId": "47bc3465-fb52-46eb-d9dd-020b97781f51"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hola, me alegra que te hayas comunicado con nosotros. Parece que hay dos problemas distintos.\n",
            "\n",
            "En cuanto a la sincronización del calendario, puedes seguir estos pasos para resolver el problema:\n",
            "\n",
            "1. Ve a Configuración > Integraciones\n",
            "2. Desconecta la integración del Calendario de Google\n",
            "3. Borra la caché y las cookies del navegador\n",
            "4. Vuelve a conectar la integración del Calendario de Google\n",
            "5. Autoriza de nuevo la aplicación en la configuración de seguridad de Google\n",
            "\n",
            "Si sigues teniendo problemas, asegúrate de que las cookies de terceros están habilitadas en la configuración de tu navegador.\n",
            "\n",
            "En cuanto al problema de subir un archivo, hay varias cosas que puedes probar:\n",
            "\n",
            "1. Comprueba el tamaño del archivo. El tamaño máximo de carga es de 100 MB.\n",
            "2. Desactiva temporalmente el antivirus o el cortafuegos.\n",
            "3. Intenta cargar el archivo en modo incógnito.\n",
            "4. Si eso no funciona, borra la caché y las cookies del navegador.\n",
            "5. Como último recurso, prueba a usar un navegador diferente.\n",
            "\n",
            "En la mayoría de los casos, el problema se debe a archivos demasiado grandes o a interferencias causadas por software de seguridad. Al seguir estos pasos, deberías poder cargar el archivo correctamente.\n",
            "\n",
            "¡Espero que esto te ayude a resolver tus problemas! Si tienes alguna otra pregunta, no dudes en preguntar.\n"
          ]
        }
      ],
      "source": [
        "print(chat_response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EVoxDcVJL8Z0"
      },
      "source": [
        "## Deleting\n",
        "\n",
        "Finally, we can delete the resources used to prevent them from consuming resources.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-gWBPxp8L8vh",
        "outputId": "4162bca7-9355-44b3-8a80-694707793739"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "<ipython-input-20-f7fb7887af9e>:2: DeprecationWarning: Passing transport options in the API method is deprecated. Use 'Elasticsearch.options()' instead.\n",
            "  es_client.indices.delete(index='multilingual-mistral', ignore=[400, 404])\n",
            "<ipython-input-20-f7fb7887af9e>:5: DeprecationWarning: Passing transport options in the API method is deprecated. Use 'Elasticsearch.options()' instead.\n",
            "  es_client.inference.delete_model(inference_id='multilingual_embeddings', ignore=[400, 404])\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "ObjectApiResponse({'acknowledged': True, 'pipelines': [], 'indexes': []})"
            ]
          },
          "execution_count": 20,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Cleanup - Delete Index\n",
        "es_client.indices.delete(index=\"multilingual-mistral\", ignore=[400, 404])\n",
        "\n",
        "# Cleanup - Delete Embeddings Endpoint\n",
        "es_client.inference.delete_model(\n",
        "    inference_id=\"multilingual_embeddings\", ignore=[400, 404]\n",
        ")"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
